package controller;

import java.io.*;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import bean.CustomerBean;

import sql.CustomerInfoLookUp;

public class Login extends HttpServlet
{
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		HttpSession session = request.getSession(true);		
		session.setAttribute("invalidUser", null);
		session.setAttribute("customer", null);
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		CustomerInfoLookUp customerInfoLookUp = new CustomerInfoLookUp();
		try 
		{
			CustomerBean customer = new CustomerBean();
			customer = customerInfoLookUp.getCustomerInfo(username, password);
			String address = "";			
			
			if(customer!= null)
			{
				session.setAttribute("customer", customer);								
				session.removeAttribute("invalidUser");				
				address = "/WEB-INF/search.jsp";
				
				RequestDispatcher dispatcher = request.getRequestDispatcher(address);
				dispatcher.forward(request, response);
			}
			else
			{
				session.setAttribute("invalidUser", "invalidUser");				
				address = "../login.jsp";
				// TODO: use RequestDispatcher instead of sendRedirect
				// i had issue directing login.jsp page which is outside WEB-INF directory
				response.sendRedirect(address);
			}

		} catch (IOException e)  { e.printStackTrace(); 
		} catch (ClassNotFoundException e) { e.printStackTrace();
		} catch (SQLException e) { e.printStackTrace(); 
		} catch (ServletException e) {e.printStackTrace();
		} 				
	}
}
